import { defineStore } from 'pinia'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:3001/api'

export const useCadreStore = defineStore('cadre', {
  state: () => ({
    cadres: [],
    loading: false,
    error: null,
    pagination: {
      page: 1,
      limit: 10,
      total: 0,
      totalPages: 0
    },
    teachingDirections: []
  }),

  getters: {
    allCadres: (state) => state.cadres,
    getCadreById: (state) => (id) => state.cadres.find(cadre => cadre._id === id)
  },

  actions: {
    async fetchCadres(params = {}) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.get(`${API_BASE_URL}/cadres`, {
          params: {
            page: params.page || 1,
            limit: params.pageSize || params.limit || 10,
            search: params.query || params.search,
            unitId: params.unitId,
            level: params.level,
            cadreType: params.cadreType,
            sortBy: params.sortBy,
            sortOrder: params.sortOrder
          }
        })

        // 处理新的响应格式 {data: {cadres: [], total: 0, ...}, message: ""}
        const data = response.data.data || response.data
        this.cadres = data.cadres || []
        this.pagination = {
          page: data.currentPage || params.page || 1,
          limit: params.pageSize || params.limit || 10,
          total: data.total || 0,
          totalPages: data.totalPages || 0
        }
        return this.cadres
      } catch (error) {
        this.error = error.response?.data?.error || '获取干部列表失败'
        console.error('获取干部列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchCadreById(id) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.get(`${API_BASE_URL}/cadres/${id}`)
        const data = response.data.data || response.data
        return data
      } catch (error) {
        this.error = error.response?.data?.error || '获取干部信息失败'
        console.error('获取干部信息失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    async addCadre(cadreData) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.post(`${API_BASE_URL}/cadres`, cadreData)
        // 重新获取完整的干部列表以确保数据一致性
        await this.fetchCadres()
        const data = response.data.data || response.data
        return data
      } catch (error) {
        this.error = error.response?.data?.error || '创建干部失败'
        console.error('创建干部失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    async updateCadre(id, cadreData) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.put(`${API_BASE_URL}/cadres/${id}`, cadreData)
        // 重新获取完整的干部列表以确保数据一致性（特别是populated数据）
        await this.fetchCadres()
        const data = response.data.data || response.data
        return data
      } catch (error) {
        this.error = error.response?.data?.error || '更新干部信息失败'
        console.error('更新干部信息失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    async deleteCadre(id) {
      this.loading = true
      this.error = null
      try {
        await axios.delete(`${API_BASE_URL}/cadres/${id}`)
        // 重新获取完整的干部列表
        await this.fetchCadres()
      } catch (error) {
        this.error = error.response?.data?.error || '删除干部失败'
        console.error('删除干部失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchTeachingDirections() {
      try {
        if (this.teachingDirections.length > 0) {
          return this.teachingDirections
        }
        const response = await axios.get(`${API_BASE_URL}/cadres/teaching-directions`)
        const data = response.data.data || response.data
        this.teachingDirections = data || []
        return this.teachingDirections
      } catch (error) {
        console.error('获取授课方向失败，将使用预设的备用数据:', error)
        this.teachingDirections = [
          "导论", "新时代坚持和发展中国特色社会主义", "以中国式现代化全面推进中华民族伟大复兴",
          "坚持党的全面领导", "坚持以人民为中心", "全面深化改革开放", "推动高质量发展",
          "社会主义现代化建设的教育、科技、人才战略", "发展全过程人民民主", "全面依法治国",
          "建设社会主义文化强国", "以保障和改善民生为重点加强社会建设", "建设社会主义生态文明",
          "维护和塑造国家安全", "建设巩固国防和强大人民军队", "坚持\"一国两制\"和推进祖国完全统一",
          "中国特色大国外交和推动构建人类命运共同体", "全面从严治党"
        ]
        return this.teachingDirections
      }
    },

    // 导出干部信息到Excel
    async exportToExcel() {
      try {
        const response = await axios.get(`${API_BASE_URL}/export/cadres`, {
          responseType: 'blob'
        })

        // 创建下载链接
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url

        // 从响应头获取文件名，如果没有则使用默认名称
        const contentDisposition = response.headers['content-disposition']
        let filename = `干部信息_${new Date().toISOString().split('T')[0]}.xlsx`
        if (contentDisposition) {
          const filenameMatch = contentDisposition.match(/filename="(.+)"/)
          if (filenameMatch) {
            filename = decodeURIComponent(filenameMatch[1])
          }
        }

        link.download = filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        return true
      } catch (err) {
        console.error('导出干部信息失败:', err)
        throw err
      }
    }
  }
})

